package com.code.lightning.utils;

import com.code.lightning.config.BasicGeneratorConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Properties配置文件解析
 * @author LGX_TvT
 * @date 2021-01-29 16:19
 */
@Slf4j
public class PropertiesUtil {

    private static final String MAPPING_REG = "template.templateMapping\\[(\\S*)\\]";

    public static BasicGeneratorConfig getConfig() {
        InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(BasicGeneratorConfig.CONFIG + ".properties");
        return getConfig(in);
    }

    public static BasicGeneratorConfig getConfig(InputStream in) {
        BasicGeneratorConfig config = new BasicGeneratorConfig();
        try {
            Properties properties = new Properties();
            properties.load(in);
            // 基础配置
            config.setLanguage(properties.getProperty("basic.language", config.getLanguage()).toUpperCase());
            config.setPackageName(properties.getProperty("basic.packageName", config.getPackageName()));
            config.setNameStyle(properties.getProperty("basic.nameStyle", config.getNameStyle()));
            config.setAuthor(properties.getProperty("basic.author", config.getAuthor()));
            config.setVersion(properties.getProperty("basic.version", config.getVersion()));
            // 数据库配置
            config.setDbCategory(properties.getProperty("db.dbCategory"));
            config.setDriver(properties.getProperty("db.driver"));
            config.setUrl(properties.getProperty("db.url"));
            config.setUser(properties.getProperty("db.user"));
            config.setPassword(properties.getProperty("db.password"));
            // includeTable 需要生成的表 全部：*, 否则使用“,” 分割
            String includeTableParam = properties.getProperty("db.includeTables", "*");
            List<String> includeTables = config.getIncludeTables();
            String[] includeSplit = includeTableParam.split(",");
            for (String s : includeSplit) {
                includeTables.add(s.trim());
            }
            // excludeTables 需要排除的表 使用“,” 分割
            String excludeTablesParam = properties.getProperty("db.excludeTables");
            if (StringUtils.isNotBlank(excludeTablesParam)) {
                String[] excludeSplit = excludeTablesParam.split(",");
                List<String> excludeTables = config.getExcludeTables();
                for (String s : excludeSplit) {
                    excludeTables.add(s);
                }
            }
            // DBCP2配置
            config.setInitialSize(Integer.parseInt(properties.getProperty("db.initialSize", config.getInitialSize().toString())));
            config.setMaxTotal(Integer.parseInt(properties.getProperty("db.maxTotal", config.getMaxTotal().toString())));
            config.setMaxIdle(Integer.parseInt(properties.getProperty("db.maxIdle", config.getMaxIdle().toString())));
            config.setMinIdle(Integer.parseInt(properties.getProperty("db.minIdle", config.getMinIdle().toString())));
            config.setMaxWaitMillis(Integer.parseInt(properties.getProperty("db.maxWaitMillis", config.getMaxWaitMillis().toString())));

            // 模板配置
            config.setTemplateBaseInputPath(properties.getProperty("template.templateBaseInputPath"));
            config.setTemplateBaseOutputPath(properties.getProperty("template.templateBaseOutputPath"));
            // 映射文件路径
            Map<String, String> templateMapping = config.getTemplateMapping();
            Set<String> mappingKeys = properties.stringPropertyNames();
            Pattern pattern = Pattern.compile(MAPPING_REG);

            // 自定义配置
            Map<String, Object> userCustomConfig = config.getUserCustomConfig();

            for (String keys : mappingKeys) {
                if (keys.startsWith("template.templateMapping")) {
                    Matcher matcher = pattern.matcher(keys);
                    while (matcher.find()) {
                        String mappingKey = matcher.group(1);
                        templateMapping.put(mappingKey, properties.getProperty(keys));
                        break;
                    }
                }

                if (keys.startsWith("user.")) {
                    String key = keys.split("\\.")[1];
                    userCustomConfig.put(key, properties.getProperty(keys));
                }
            }
            return config;
        } catch (IOException e) {
            log.error("load properties error, {}", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}
